package com.example.demo.service;

import cn.hutool.json.JSONUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author: Bin.L
 * @date: 2021/11/18  15:22
 * @Description: 钉钉自定义机器人消息推送 {https://developers.dingtalk.com/document/robots/custom-robot-access/title-72m-8ag-pqw}
 */

@Slf4j
@Service
public class DingTalkAiService {

    @Value("https://oapi.dingtalk.com/robot/send?access_token=f15ec95835d8ee60685e12c4423e5aaf4e51c33f6df841feccc54559ad4d09a1")
    private String access;

    /**
     * 钉钉文本消息
     *
     * @param textContent 文本内容
     */
    public void pushTextMessage(String textContent) {
        DingTalkClient client = new DefaultDingTalkClient(access);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");

        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        // 消息 为发送前缀（自定义验证规则）
        text.setContent("消息: " + textContent);
        request.setText(text);

        try {
            OapiRobotSendResponse response = client.execute(request);
            log.info("发送钉钉AI返回结果: {}", JSONUtil.toJsonStr(response));
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }


    /**
     * 钉钉Markdown消息
     *
     * @param markdownContent
     */
    public void pushMarkdownMessage(String markdownContent) {
        DingTalkClient client = new DefaultDingTalkClient(access);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("markdown");

        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle("消息");
        markdown.setText(markdownContent);
        request.setMarkdown(markdown);

        try {
            OapiRobotSendResponse response = client.execute(request);
            log.info("发送钉钉AI返回结果: {}", JSONUtil.toJsonStr(response));
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

}
